package xin.common.io;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <pre>
 * 限速下载
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2019/4/26
 */
@Controller
@RequestMapping
public class LimitController {

    @GetMapping("limit")
    public void downloadLimit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File("E:\\app\\java.zip");
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Type","application/x-zip-compressed");
        response.setHeader("Content-Disposition","attachment; filename=data.zip");

        BandwidthLimiter band = new BandwidthLimiter(320);
        LimitOutputStream los = new LimitOutputStream(response.getOutputStream(),band);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[1024];
        int length;
        while ((length = bis.read(buffer))!= -1){
            los.write(buffer,0,length);
        }
    }
}
